package com.dotnet.modules.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dotnet.common.utils.AddressUtils;
import com.dotnet.common.web.BaseController;
import com.dotnet.modules.city.entity.City;
import com.dotnet.modules.city.service.CityService;
import com.dotnet.modules.product.entity.ProductInfo;
import com.dotnet.modules.product.service.ProductInfoService;
import com.shishuo.cdn.util.ClientIPUtils;

@Controller
@RequestMapping("/web/")
public class WebController extends BaseController{

	@Autowired
	private ProductInfoService productInfoService;
	
	@Autowired
	private CityService cityService;

	@RequestMapping("/toShowIndex.do")
	public String toIndex(ModelMap model,String cityName,HttpServletRequest request) {
		logger.info("进入首页展示---");
		ProductInfo productInfo = new ProductInfo();
		productInfo.setIsUse(1);
		productInfo.setIsDelete(0);
		productInfo.setIsUseIndex(1);
		if(null!=cityName && StringUtils.isNotBlank(cityName)){
			productInfo.setCityName(cityName);
			model.put("cityName", cityName);
			request.getSession().setAttribute("cityName", cityName);
		}else{
			productInfo.setCityName("北京");
			model.put("cityName", "北京");
			request.getSession().setAttribute("cityName", "北京");
		}
		List<ProductInfo> queryAll = productInfoService.queryAll(productInfo);
		if(null!=queryAll && queryAll.size()>0){
			model.put("list", queryAll);
		}
		City city = new City();
		city.setIsDelete(0);
		List<City> cityList = cityService.queryAll(city);
		if(null!=cityList && cityList.size()>0){
			model.put("cityList", cityList);
			request.getSession().setAttribute("cityList", cityList);
		}
		
		//首次进来时，cityName 默认为空 , 以IP获取
		//上面设置默认城市为 北京 
		//根据ip先获取地址
		//在city表里比较，如果存在则替换上面所设置的默认城市
		//如果不存在，则默认为北京
		if(null==cityName || StringUtils.isBlank(cityName)){
			String ip = ClientIPUtils.getIpAddr(request);
			AddressUtils addressUtils = new AddressUtils();
			String address = "";
			try {
				address = addressUtils.getAddress("ip=" + ip, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if(null!=address && StringUtils.isNotBlank(address)){
				for (City ct : cityList) {
					if(address.contains(ct.getCityName())){
						System.out.println("ip为:"+ip+"-->所对应城市为:"+address);
						System.out.println("当前库中所匹配城市为:"+ct.getCityName());
						model.put("cityName", ct.getCityName());
						request.getSession().setAttribute("cityName", ct.getCityName());
					}else{
						System.out.println(address+"--和--"+ct.getCityName()+"--不匹配!");
					}
				}
			}
		}
		
		return "/index";
	}
}
